package edu.cdnu.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import edu.cdnu.common.constant.MessageConstatnt;
import edu.cdnu.common.dto.CommonUserDto;
import edu.cdnu.common.dto.DepartmentSubjectClass;
import edu.cdnu.common.request.CommonUserLoginRequest;
import edu.cdnu.common.result.ResultEntity;
import edu.cdnu.pojo.DictionaryPojo;
import edu.cdnu.service.CommonService;
import edu.cdnu.utils.TypeConversionUtils;

/**
 * 一些通用的操作
 * 各个角色都可能用得到
 * @author ASUS AsingZ
 */
@RestController
@RequestMapping("/common")
public class CommonController {
	
	@Autowired
	private CommonService commonService;
	
	/**
	 * 登录接口
	 * @param userReq
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/login")
	public ResultEntity<?> login(@RequestBody CommonUserLoginRequest userReq,HttpServletRequest request,HttpServletResponse response) {
		//获得subject
		Subject subject=SecurityUtils.getSubject();
		
		// 判断是否登录
		if(subject.isAuthenticated()) {
			// 已经登录直接返回
			ResultEntity.createSuccessResult(null,"已经登录过了");
		}
		
		// 没有登录进行操作		
		//生成token----这里username传的是account+role用于realm在验证时判断
		String accountRole=userReq.getAccount()+"."+userReq.getRoleId();
		UsernamePasswordToken token=new UsernamePasswordToken(accountRole,userReq.getPassword());

		try {
			// 认证
			subject.login(token);
		} catch (AuthenticationException e) {
			return ResultEntity.createFailResult(MessageConstatnt.USER_PWD_FAIL);
		}
		
		return ResultEntity.createSuccessResult(null,"登录成功");
	}
	
	
	/**
	 * 有些时候直接访问网站首页，是登录状态但是前端的数据丢失，在这获取登录状态和登录信息
	 * @return
	 */
	@GetMapping("/logedInfo")
	public ResultEntity<CommonUserDto> testLoged() {
		Subject subject=SecurityUtils.getSubject();
		CommonUserDto userInfo=null;
		// 登录了返回数据
		if(subject.isAuthenticated()) {
			userInfo=TypeConversionUtils.subjectPrincipalToCommonUserDto(subject.getPrincipal());
		}
		if(userInfo!=null) {
			return ResultEntity.createSuccessResult(userInfo);
		}
		return ResultEntity.createFailResult(MessageConstatnt.UNLOGIN);
		
	}
	
	/**
	 * 查询所有学院（系部）
	 * 后面单词还是用department 但叫法为学院不是系部
	 * @return
	 */
	@GetMapping("/departmentList")
	public ResultEntity<List<DictionaryPojo>> selectAllDepartmentList(){
		return ResultEntity.createSuccessResult(commonService.selectAllDepartmentList());
	}
	
	/**
	 * 通过数据字典表的描述信息来查询字典列表
	 * @param decription
	 * @return
	 */
	@GetMapping("/dictionary")
	public ResultEntity<List<DictionaryPojo>> selectDictionaryListByDecription(@RequestParam String decription){
		if(decription != null && !"".equals(decription)) {
			return ResultEntity.createSuccessResult(commonService.selectDictionaryListByDecription(decription));
		}
		return ResultEntity.createFailResult(MessageConstatnt.GET_INFO_FAIL);
	}
	
	/**
	 * 通过父id来查询字典列表
	 * @param parentId
	 * @return
	 */
	public ResultEntity<List<DictionaryPojo>> selectDictionaryListByParentId(@RequestParam Integer parentId){
		if(parentId != null) {
			return ResultEntity.createSuccessResult(commonService.selectDictionaryListByParentId(parentId));
		}
		return ResultEntity.createFailResult(MessageConstatnt.GET_INFO_FAIL);
	}
	
	/**
	 * 学院专业班级 整合的数据
	 * 
	 * @return
	 */
	@GetMapping("/departmentSubejctClass")
	public ResultEntity<?> selectDepartmentSubjectClassList(){
		List<DepartmentSubjectClass<?>> list=new ArrayList<>();
		List<DepartmentSubjectClass<?>> subjectList=new ArrayList<>();
		List<DepartmentSubjectClass<?>> classList=new ArrayList<>();
		
		List<DictionaryPojo> department=commonService.selectDictionaryListByDecription("学院");
		List<DictionaryPojo> subject=commonService.selectDictionaryListByDecription("专业");
		List<DictionaryPojo> clazz=commonService.selectDictionaryListByDecription("班级");
		
		clazz.forEach(item->{
			classList.add(new DepartmentSubjectClass<>(item.getId(),item.getName(),item.getParentId(),item.getDecription(),null));
		});
		
		subject.forEach(item->{
			List<DepartmentSubjectClass<?>> arr=classList.stream().filter(classItem->{
				return classItem.getParentId()==item.getId();
			}).collect(Collectors.toList());
			
			subjectList.add(new DepartmentSubjectClass<>(item.getId(),item.getName(),item.getParentId(),item.getDecription(),arr));
		});
		
		department.forEach(item->{
			List<DepartmentSubjectClass<?>> arr=subjectList.stream().filter(subjectItem->{
				return subjectItem.getParentId()==item.getId();
			}).collect(Collectors.toList());
			
			list.add(new DepartmentSubjectClass<>(item.getId(),item.getName(),item.getParentId(),item.getDecription(),arr));
		});
		
		return ResultEntity.createSuccessResult(list);
	}
	
}
